/**
 * 本类用于与PC端服务器连接与交互
 * */

package com.yunxiangyue.server

import android.util.ArrayMap
import android.util.Log
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.yunxiangyue.logger.Logger
import com.yunxiangyue.musicplayer.Music
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import okhttp3.Call
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import org.json.JSONObject
import java.io.ByteArrayOutputStream

import java.io.IOException
import java.util.HashMap

val byteArray = HashMap<String, ByteArray>()
const val MUSIC_REQUEST = 1
const val USER_INSERTREQUEST = 2
const val USER_UPDATEREQUEST = 3
const val USER_DELETEREQUEST = 4
const val USER_MUSICLISTREQUEST = 5
//判断用户的信息是否存在远程的事件
const val USERINFO_JUDGE = 0

const val TAG = "PCServerConnectManager"

class PCServerConnectManager {
    val ServerAddress = "http://192.168.3.133:8080/tomcat/"
//    172.20.10.13   192.168.3.133
    var callback =  object: okhttp3.Callback{
        override fun onFailure(call: Call, e: IOException) {
            Logger.error(TAG, "error called no implement")
        }

        override fun onResponse(call: Call, response: Response) {
            Logger.error(TAG, "error called no implement")
        }

    }

    fun connect(ip: String, port: Int) {

    }

    //发送请求消息  通过event判断发送的请求类型
    //1：请求所有的音乐资源文件
    //2：请求添加用户信息
    //3：请求修改用户信息
    //4: 请求删除用户信息
    //5: 请求指定用户的歌单信息，可以借用索引

    // suspend
//    fun send(endPoint:String, event:Int, map: androidx.collection.ArrayMap<String, String>): String {
//            val client = OkHttpClient()
//
//            val phone = map[OkHttpKeyUtil.KEY_USER_INFO_PHONE]
//            val pwd = map[OkHttpKeyUtil.KEY_USER_INFO_PASSWORD]
//            val nike = map[OkHttpKeyUtil.KEY_USER_INFO_NAME]
//            val userType = map[OkHttpKeyUtil.KEY_USER_INFO_TYPE]
//
//            Log.d("user",phone.toString()+":"+pwd.toString()+":"+nike.toString()+":"+userType.toString())
//            when(event){
//                0 -> {
//                    //判断是否存在数据库中
//                    var result: String = ""
//
//                    //开启协程，处理异步操作：如网络请求和数据库请求
//                    GlobalScope.launch {
//                        Log.d("user", "事件是: $event")
//                        val requestBody: RequestBody = FormBody.Builder()
//                            .add("eventType", USERINFO_JUDGE.toString())
//                            .add("userPhone", phone.toString())
//                            .build()
//                        val request = Request.Builder()
//                            .url(ServerAddress + endPoint)
//                            .post(requestBody)
//                            .build()
//
//                        // 同步请求
//                        val response = client.newCall(request).execute()
//                        val content = response.body?.string()
//                        val jsonObject = JSONObject(content)
//                        result = jsonObject.get("userIfExists").toString()
//                    }
//
////                    latch.await() // 主线程等待，直到计数器为0
//                    return result.toString()
//
//                }
//
//
//                1 -> {
//                    //请求所有的音乐文件  不需要请求体  直接发送请求后获取
//                    val request = Request.Builder()
//                        .url(ServerAddress+endPoint)
//                        .get()
//                        .build()
//                    //为该请求注册异步回调函数
//                    // scope.launch
//                    callback.let {
//                        client.newCall(request).enqueue(it)
//                    }
//                }
//
//                3 -> {
//                    //请求修改用户信息
//                    val requestBody:RequestBody = FormBody.Builder()
//                        .add("eventType", USER_UPDATEREQUEST.toString())
//                        .add("userPhone",phone.toString())
//                        .build()
//                    val request:Request = Request.Builder()
//                        .url(ServerAddress+endPoint)
//                        .post(requestBody)
//                        .build()
//                    callback.let {
//                        client.newCall(request).enqueue(it)
//                    }
//                }
//
//                4 -> {
//                    //请求删除用户信息
//                    val requestBody:RequestBody = FormBody.Builder()
//                        .add("eventType", USER_DELETEREQUEST.toString())
//                        .add("userPhone",phone.toString())
//                        .build()
//                    val request:Request = Request.Builder()
//                        .url(ServerAddress+endPoint)
//                        .post(requestBody)
//                        .build()
//                    callback.let {
//                        client.newCall(request).enqueue(it)
//                    }
//                }
//
//
//            }
//
//        return "不属于任何一个事件"
//    }

    //添加用户的信息
    fun send(path: String, requestBody: RequestBody, callback: (Boolean, ByteArray)->Unit) {
        val client = OkHttpClient()


//        GlobalScope.launch

        //请求添加用户信息
        //解析json字符串
        CoroutineScope(Dispatchers.Default).launch{
                val request:Request = Request.Builder()
                    .url(ServerAddress+path)
                    .post(requestBody)
                    .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                    .build()
                client.newCall(request).enqueue(object : okhttp3.Callback{
                    override fun onFailure(call: Call, e: IOException) {
                        Log.d(TAG, "请求失败")
                        e.printStackTrace()
                    }

                    override fun onResponse(call: Call, response: Response) {
                        val result = response.isSuccessful
                        val bytes = mutableListOf<Byte>()
                        if (result) {
                            val buffer = ByteArray(1000)
                            while (response.body?.byteStream()?.read(buffer) != -1) {
                                bytes.addAll(buffer.map { it.toByte() })
                            }
                        }

                        callback(result, bytes.toByteArray())
                    }
                })
        }

//        GlobalScope.cancel()
    }


    //单独写一个获取数据库音乐文件的方法
//    fun sendMusicRequest(path: String, requestBody: RequestBody, callback: (Boolean, ByteArray) -> Unit) {
//        val client = OkHttpClient()
//        //请求添加用户信息
//        //解析json字符串
//        CoroutineScope(Dispatchers.Default).launch{
//            val request:Request = Request.Builder()
//                .url(ServerAddress+path)
//                .post(requestBody)
//                .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
//                .build()
//            client.newCall(request).enqueue(object : okhttp3.Callback{
//                override fun onFailure(call: Call, e: IOException) {
//                    Log.d(TAG, "请求失败")
//                    e.printStackTrace()
//                }
//
//                override fun onResponse(call: Call, response: Response) {
//                    val result = response.isSuccessful
//                    val bytes = mutableListOf<Byte>()
//                    if (result) {
//                        val buffer = ByteArray(1000)
//                        while (response.body?.byteStream()?.read(buffer) != -1) {
//                            bytes.addAll(buffer.map { it.toByte() })
//                        }
//                    }
//
//                    callback(result, bytes.toByteArray())
//                }
//            })
//        }
//
////        GlobalScope.cancel()
//    }


    fun sendMusicName(path: String, requestBody: RequestBody, callback: (Boolean, ByteArray) -> Boolean) {
        val client = OkHttpClient()
        //请求添加用户信息
        //解析json字符串
        CoroutineScope(Dispatchers.Default).launch{
            val request:Request = Request.Builder()
                .url(ServerAddress+path)
                .post(requestBody)
                .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .build()
            client.newCall(request).enqueue(object : okhttp3.Callback{
                override fun onFailure(call: Call, e: IOException) {
                    Log.d(TAG, "请求失败")
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    val result = response.isSuccessful
                    val bytes = mutableListOf<Byte>()
                    if (result) {
                        val buffer = ByteArray(1000)
                        while (response.body?.byteStream()?.read(buffer) != -1) {
                            bytes.addAll(buffer.map { it.toByte() })
                        }
                    }

                    callback(result, bytes.toByteArray())
                }
            })
        }

//        GlobalScope.cancel()
    }
}


